let app = getApp();
Page({
  data: {
    index: 0,
    name: '',
    isShow: true,
    password: '',
    submit: true,
    longitude: '',
    latitude: '',
  },

  onLoad: function(options) {
    let name = decodeURIComponent(options.name);
    let openid = wx.getStorageSync('openid');
    let that = this;
    this.setData({
      name,
      openid,
    });
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        let latitude = res.latitude;
        let longitude = res.longitude;
        that.setData({ latitude, longitude });
      },
    });
  },

  onReady: function() {

  },

  onShow: function() {
    let that = this;
    setInterval(function() {
      Number(that.data.index) !== 3 ? that.setData({
        index: that.data.index + 1,
      }) : that.setData({
        index: 0,
      });
    }, 500);
  },

  bindinput: function(e) {
    let password = e.detail.value;
    this.setData({
      password,
    });
    if (password.length > 7) this.setData({ submit: false });
  },

  cancel: function() {
    wx.navigateBack();
  },

  makeSure: function() {
    let name = this.data.name;
    let password = this.data.password;
    let openid = this.data.openid;
    let that = this;
    this.setData({ isShow: false });
    wx.startWifi({
      success: function(res) {
        wx.connectWifi({
          SSID: name,
          password: password,
          success(res) {
            wx.getConnectedWifi({
              success: function (res) {
                let onname = res.wifi.SSID || '';
                if (onname == name) {
                  that.sendMes(name, password, openid);
                } else {
                  app.util.navigateTo('/cm_wifi/pages/error/error', { name }, false);
                }
              },
              fail: function (res) {
                app.util.navigateTo('/cm_wifi/pages/error/error', { name }, false);
              },
            });
          },
          fail(res) {
            app.util.navigateTo('/cm_wifi/pages/error/error', { name }, false);
          },
        });
      },
    });
  },

  sendMes: function (wifi_name, wifi_password, openid) {
    let location = this.data.longitude + ',' + this.data.latitude;
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        wifi_name,
        wifi_password,
        openid,
        op: 'addWifiRecord',
        location,
      },
      module: 'cm_wifi',
      success: function(res) {
      },
    });
  },

  enter: function(e) {
    this.setData({
      password: e.detail.value,
    });
  },

  onHide: function() {

  },

  onUnload: function() {

  },

  onPullDownRefresh: function() {

  },

  onReachBottom: function() {

  },

});